import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import LoginView from '../views/LoginView.vue'
import RegisterView from '../views/RegisterView.vue'
import UserListView from '../views/UserListView.vue'
import UserProfileView from '../views/UserProfileView.vue'
import NotFound from '../views/NotFound.vue'
import store from '../store/index';


const routes = [{
        path: '/myspace/home/',
        name: 'home',
        component: HomeView,
        meta: {
            requestAuth: true,
        }
    },
    {
        path: '/myspace/userlist/',
        name: 'userlist',
        component: UserListView,
        meta: {
            requestAuth: true,
        }
    },
    {
        path: '/myspace/userprofile/:userId/',
        name: 'userprofile',
        component: UserProfileView,
        meta: {
            requestAuth: true,
        }
    },
    {
        path: '/myspace/login/',
        name: 'login',
        component:LoginView,
        meta: {
            requestAuth: false,
        }
    },
    {
        path: '/myspace/register/',
        name: 'register',
        component: RegisterView,
        meta: {
            requestAuth: false,
        }
    },
    {
        path: '/myspace/404/',
        name: '404',
        component: NotFound,
        meta: {
            requestAuth: false,
        }
    }
]


const router = createRouter({
    history: createWebHistory(),
    routes
});

router.beforeEach((to, from, next) => {
    if(to.meta.requestAuth && !store.state.user.is_login) {
        next({name: 'login'});
    }else {
        next();
    }
})

export default router